package src.leetcode.greedy.medium_0056;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class merge {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int [][] arr = new int[][]{{2, 6}, {1, 3}, {8, 10}, {15, 18}};
        System.out.println(Arrays.deepToString(arr));
        System.out.println(Arrays.deepToString(solution.merge(arr)));
        System.out.println(Arrays.deepToString(arr));
    }
}

class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(x -> x[0]));

        List<int[]> ans = new ArrayList<>();
        int left = intervals[0][0], right = intervals[0][1];
        for(int i = 1; i < intervals.length; i++){
            if(intervals[i][0] <= right) right = Math.max(right, intervals[i][1]);
            else{
                ans.add(new int[]{left, right});
                left = intervals[i][0];
                right = intervals[i][1];
            }
        }

        ans.add(new int[]{left, right});
        return ans.toArray(new int[ans.size()][]);
    }
}


